package com.hjy.im.client;

import com.hjy.im.message.*;
import com.hjy.im.protocol.MessageSharableCodec;
import com.hjy.im.protocol.ProcotolFrameDecoder;
import com.hjy.im.server.handler.RpcRequestMessageHandler;
import com.hjy.im.server.handler.RpcResponseMessageHandler;
import com.hjy.im.server.service.UserService;
import com.hjy.im.server.service.UserServiceMemoryImpl;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class RPCClient {
    static final Logger log = LoggerFactory.getLogger(RPCClient.class);
    /**
        * 产生SequenceId
     */
    private static AtomicInteger sequenceId = new AtomicInteger(0);
    private static volatile Channel channel = null;
    private static final Object lock = new Object();
    public static void main(String[] args) {
        UserService service = (UserService) getProxy(UserService.class);
        String test = service.sayHello("test");
        System.out.println(test+"ccccccccccc");
    }


    /**
     * 使用代理模式，帮助我们创建请求消息并发送
     */
    private static Object getProxy(Class<?> serviceClass) {
        Class<?>[] classes = new Class<?>[]{serviceClass};
        System.out.println("get proxy start ...");
        //使用jdk 代理，创建代理对象
        Object o = Proxy.newProxyInstance(serviceClass.getClassLoader(), classes, new InvocationHandler() {
                        @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("invoke start ....");
                //创建请求信息
                int id = sequenceId.getAndIncrement();
                            System.out.println("get id "+id);
                RpcRequestMessage message = new RpcRequestMessage(id, serviceClass.getName(), method.getName(), method.getReturnType(),
                        method.getParameterTypes(), args);
                            System.out.println("get channle  ..."+getChannel());
                //发送消息
                getChannel().writeAndFlush(message);
                            System.out.println("invoke get channel ...");
                //创建 Promis 用于获取 nio 线程中返回的结果,获取的过程是异步的
                DefaultPromise<Object> promise = new DefaultPromise<>(getChannel().eventLoop());
                //将Promis 放入到Map 中
                RpcResponseMessageHandler.promiseMap.put(id, promise);
                System.out.println("wait promise");
                //等待放入到Promise 中的结果
                promise.await();
                            System.out.println("result"+promise.isSuccess());
                if (promise.isSuccess()) {
                    //调换成功，获取返回结果
                    return promise.getNow();
                } else {
                    //调用失败，返回异常
                    throw new RuntimeException(promise.cause());
                }
            }
        });
        return o;

    }

    public static Channel getChannel() {
        if (channel == null){
            synchronized (lock){
                if ((channel == null)){
                    init();
                }
            }
        }
        return channel;
    }

    private static void init() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        MessageSharableCodec messageSharableCodec = new MessageSharableCodec();
        //rpc 请求处理器
        RpcResponseMessageHandler rpcResponseMessageHandler = new RpcResponseMessageHandler();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(group);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new ProcotolFrameDecoder());
                socketChannel.pipeline().addLast(loggingHandler);
                socketChannel.pipeline().addLast(messageSharableCodec);
                socketChannel.pipeline().addLast(rpcResponseMessageHandler);
            }
        });
        System.out.println("init connect...");
        try{
            channel = bootstrap.connect(new InetSocketAddress("localhost", 9090)).sync().channel();
            System.out.println("channel "+channel);
            //异步关闭group 避免 channel 阻塞
            channel.closeFuture().addListener(future -> {
               group.shutdownGracefully();
            });
        }catch (InterruptedException e){
            System.out.println("channel error");
            e.printStackTrace();
        }


    }
}
